<script setup lang="ts">

import {Check, Close, Delete, Edit, Plus, Refresh, Search} from "@element-plus/icons-vue";
import {reactive, ref} from "vue";
import request from "@/utils/request";
import {ElMessage, UploadProps} from "element-plus";
import {getToken} from "@/utils/auth";
const addGiftImg = reactive({'Authorization': 'Bearer ' + getToken()});
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.type !== 'image/jpeg') {
        ElMessage.error('图片必须是jpg/jpeg格式');
        return false;
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('Avatar picture size can not exceed 2MB!');
        return false;
    }
    return true;
};
//表单验证规则
const elRef = ref(null);
const rules = ref({
    title: [{
        required: true,
        message: '请输入业务名称',
        trigger: 'blur'
    }],
    sort: [{
        required: true,
        message: '请输入排序',
        trigger: 'blur'
    }],
    intro: [{
        required: true,
        message: '请输入简介',
        trigger: 'blur'
    }],
});

//加载页面数据======================================================
const times=ref([]);
function getPageData(query) {
    return request({
        url: '/jsMemoir/page',
        method: 'get',
        params: query
    });
}


const searchData = ref({
    title: '',
    timeRange: ``,
    jsBusinessType: 'js_trends',
    pageNum: 1,
    pageSize: 10,
});
const pageData = ref<object[]>([]);
getPageData(searchData.value).then((res) => {
    console.log(res);
    pageData.value?.push((res as any).rows);
    pageDatatotal.value = (res as any).total;
});

//查询==================================================================


function search() {
    pageData.value.length = 0;
    if (times.value.length!==0){
        searchData.value.timeRange=`${times.value[0]},${times.value[1]}`;
    }else
    {
        searchData.value.timeRange='';
    }

    getPageData(searchData.value).then((res) => {
        pageData.value?.push((res as any).rows);
        pageDatatotal.value = (res as any).total;
    });
}

//重置================================================================
function reset() {
    times.value.length=0;
    searchData.value.timeRange='';
    searchData.value.title = '';
    pageData.value.length = 0;
    getPageData(searchData.value).then((res) => {
        pageData.value?.push((res as any).rows);
        pageDatatotal.value = (res as any).total;
    });
}

//新增==================================================================
const addImg=ref('');
const addhandleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    addImg.value = URL.createObjectURL(uploadFile.raw!);
    addformData.value.mainPic = (uploadFile as any).response.fileName;
};
const addDialog = ref(false);
const addformData = ref({
    jsBusinessType: "js_trends",
    title: '',
    intro: '',
    sort:null,
    mainPic:'',
    contentRich:''
});

function addNewData() {
    addDialog.value = true;
    addformData.value.mainPic=addImg.value;
}

function addNewDataFn(query) {
    return request({
        url: '/jsMemoir',
        method: 'post',
        data: query
    });
}

function addsubmitForm() {
    (elRef as any).value.validate((valid) => {
        if (valid) {
            addNewDataFn(addformData.value).then(() => {
                ElMessage.success('提交成功');
                pageData.value.length = 0;
                getPageData(searchData.value).then((res) => {
                    pageData.value?.push((res as any).rows);
                    pageDatatotal.value = (res as any).total;
                });
                addDialog.value = false;
                addImg.value='';
                addformData.value.intro=' ';
                addformData.value.sort=null;
                addformData.value.title='';
                addformData.value.contentRich=' ';
            });

        } else {
            ElMessage.error('提交失败');
            return false;
        }
    });
};
//修改单条数据=============================================
const changeImg=ref('');
const changeDialog = ref(false);
const changeformData = ref({
    jsBusinessType: "js_trends",
    title: '',
    intro: '',
    sort:null,
    mainPic:'',
    memoirId:'',
    contentRich:''
});

function changeOnceData(id) {
    changeformData.value.memoirId = id;
    changeDialog.value = true;
    getOnceData(id).then(res => {
        changeformData.value.intro = res.data.intro;
        changeformData.value.title = res.data.title;
        changeformData.value.sort = res.data.sort;
        changeImg.value = '/dev-api'+res.data.mainPic;
        changeformData.value.mainPic=res.data.mainPic;
    });
}

function getOnceData(id) {
    return request({
        url: `/jsMemoir/${id}`,
        method: 'get',
    });
}

function changeDataFn(query) {
    return request({
        url: '/jsMemoir',
        method: 'put',
        data: query
    });
}

function changesubmitForm() {
    (elRef as any).value.validate((valid) => {
        if (valid) {
            changeDataFn(changeformData.value).then(() => {
                ElMessage.success('提交成功');
                pageData.value.length = 0;
                getPageData(searchData.value).then((res) => {
                    pageData.value?.push((res as any).rows);
                    pageDatatotal.value = (res as any).total;
                });
                changeDialog.value = false;
            });

        } else {
            ElMessage.error('提交失败');
            return false;
        }
    });
};
const changehandleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    changeImg.value = URL.createObjectURL(uploadFile.raw!);
    changeformData.value.mainPic = (uploadFile as any).response.fileName;
};
//删除单条数据========================================
const deleteDialog = ref(false);
const DeleteId = ref();

function deleteDataFn(id) {
    return request({
        url: `/jsMemoir?memoirIdList=${id}`,
        method: 'delete',
    });
}

function deleteOnceData(id) {
    DeleteId.value = id;
    deleteDialog.value = true;
}

function sureDelete() {
    deleteDataFn(DeleteId.value).then(() => {
        ElMessage.success('删除成功');
        pageData.value.length = 0;
        getPageData(searchData.value).then((res) => {
            pageData.value?.push((res as any).rows);
            pageDatatotal.value = (res as any).total;
        });
        deleteDialog.value = false;
    });
}

//分页===================================================
const pageDatatotal = ref(0);
const handleCurrent = (val: number) => {
    searchData.value.pageNum = val;
    pageData.value.length = 0;
    getPageData(searchData.value).then(res => {
        pageData.value?.push((res as any).rows);
    });
};

//取消操作===================================
function cencelAction() {
    deleteDialog.value = false;
    addDialog.value = false;
    changeDialog.value = false;
    ElMessage('取消操作');
}
//改变开关状态
let changeActviteData = ref({
    displaying: 0,
    memoirId:null,
    mainPic:'',
});
function changeActiveStatus(id) {
    getOnceData(id.row.memoirId).then((res)=>{
        console.log(id.row.displaying);
        if(res.data.displaying===0){
            changeActviteData.value.displaying=1;
        }else {
            changeActviteData.value.displaying=0;
        }
        changeActviteData.value.mainPic=res.data.mainPic;
        changeActviteData.value.memoirId = id.row.memoirId;
        changeDataFn(changeActviteData.value).then(() => {
            ElMessage({
                message: '修改成功！',
                type: 'success',
            });
        });
    });


}
</script>
<template>
    <div>
        <div class="title" style="position: relative">
            <span class="inputTitle">标题名称</span>
            <el-input
                v-model="searchData.title"
                class="activeName"
                placeholder="请输入标题名称"
                clearable
                size="large"
            />
            <span class="inputTitle">创建时间</span>
            <el-date-picker
                v-model="times"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                clearable
                size="default"
                value-format="YYYY-MM-DD"
            />
            <span class="btns">
            <el-button type="primary" :icon="Search" class="serachBtn" @click="search">查询</el-button>
            <el-button :icon="Refresh" class="refreshBtn" @click="reset">重置</el-button>
        </span>
        </div>
        <section class='tableBox' style="padding: 0 30px">
            <el-button type="primary" :icon="Plus" style="margin-top: 20px;" @click="addNewData">新增</el-button>
            <el-table :data="(pageData[0] as any)" style="width: 100%;margin-top: 50px" stripe>
                <template #empty>
                    <el-empty description="暂无数据"/>
                </template>
                <el-table-column prop="title" label="业务名称" height/>
                <el-table-column prop="createdTime" label="时间" height/>
                <el-table-column prop="sort" label="排序" height/>
                <el-table-column prop="displaying" label="是否展示" height>
                    <template #default="appIndex">
                        <el-switch
                            v-model=appIndex.row.displaying
                            class="mt-2"
                            style="margin-top: 0"
                            inline-prompt
                            :active-icon="Check"
                            :inactive-icon="Close"
                            :active-value="1"
                            :inactive-value="0"
                            @click="changeActiveStatus(appIndex)"
                        />
                    </template>

                </el-table-column>
                <el-table-column prop="操作" label="操作" height>
                    <template #default="index">
                        <el-button style="color: #1c84c6;" @click="changeOnceData(index.row.memoirId)" :icon="Edit">修改</el-button>
                        <el-button style="color: #1c84c6;margin-left: 20px" @click="deleteOnceData(index.row.memoirId)" :icon="Delete">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </section>
        <div style="position: relative">
            <span style="margin-left: 1000px;position: absolute;top: 8px">共{{ pageDatatotal }}条数据</span>
            <el-pagination
                style="margin-top: 20px;margin-left: 1150px"
                :page-size="searchData.pageSize"
                layout="prev, pager, next"
                :total="pageDatatotal"
                @currentChange="handleCurrent"
            />
        </div>
        <el-dialog v-model="deleteDialog" title="提示" width="500" center>
            <el-icon color="rgb(255, 186, 0)" size="25">
                <Warning/>
            </el-icon>
            <span style="font-size: 20px;vertical-align: top;margin-left: 10px">进行删除操作后无法恢复，是否继续删除？</span>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="cencelAction">取消</el-button>
                    <el-button type="primary" @click="sureDelete">
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>
        <el-dialog v-model="addDialog" title="新增" width="800" style="padding: 20px">
            <el-form ref="elRef" :model="addformData" :rules="rules">
                <el-form-item label="标题：" prop="title">
                    <el-input
                        v-model="addformData.title"
                        placeholder="请输入标题"
                        clearable
                        size="large"></el-input>
                </el-form-item>
                <el-form-item label="简介：" prop="intro">
                    <el-input
                        v-model="addformData.intro"
                        placeholder="请输入简介"
                        clearable
                        type="textarea"
                        resize="none"
                        size="large"></el-input>
                </el-form-item>
                <el-form-item label="排序：" prop="sort">
                    <el-input-number
                        v-model="addformData.sort"
                        :min="0"
                        :precision="0"
                        size="large"
                        controls-position="right"
                    />
                </el-form-item>
                <el-form-item label="内容：" prop="contentRich">
                    <editor
                        v-model="addformData.contentRich"
                        :min="0"
                        :precision="0"
                        size="large"
                        controls-position="right"
                    />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer" style="margin-left: 560px">
                    <el-form-item>
                        <el-button size="large" @click="cencelAction">取消</el-button>
                        <el-button type="primary" size="large" @click="addsubmitForm">确定</el-button>
                    </el-form-item>
                </div>
            </template>
        </el-dialog>
        <el-dialog v-model="changeDialog" title="新增" width="800" style="padding: 20px">
            <el-form ref="elRef" :model="changeformData" :rules="rules">
                <el-form-item label="标题：" prop="title">
                    <el-input
                        v-model="changeformData.title"
                        placeholder="请输入标题"
                        clearable
                        size="large"></el-input>
                </el-form-item>
                <el-form-item label="简介：" prop="intro">
                    <el-input
                        v-model="changeformData.intro"
                        placeholder="请输入简介"
                        clearable
                        type="textarea"
                        resize="none"
                        size="large"></el-input>
                </el-form-item>
                <el-form-item label="排序：" prop="sort">
                    <el-input-number
                        v-model="changeformData.sort"
                        :min="0"
                        :precision="0"
                        size="large"
                        controls-position="right"
                    />
                </el-form-item>
                <el-form-item label="内容：">
                    <editor
                        v-model="changeformData.contentRich"
                        :min="0"
                        :precision="0"
                        size="large"
                        controls-position="right"
                    />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer" style="margin-left: 560px">
                    <el-form-item>
                        <el-button size="large" @click="cencelAction">取消</el-button>
                        <el-button type="primary" size="large" @click="changesubmitForm">确定</el-button>
                    </el-form-item>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<style scoped>
.title {
    height: 65px;
    border-bottom: 1px solid rgb(237, 237, 237);
    line-height: 65px;
    padding: 0 45px;
    overflow: hidden;
}

.inputTitle {
    font-size: 14px;
    font-weight: bolder;
    color: #666;
    margin-right: 20px;
    margin-left: 20px;

}

.btns {
    margin-left: 80px;
}

.activeName {
    width: 15%;
    margin-left: -5px;
    margin-right: 15px;
    height: 28px;
    font-size: 12px;
}

/deep/ .cell {
    text-align: center;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    font-size: 16px !important;
}
/deep/ .el-form-item__label {
    width: 15% !important;
}

/deep/ .ql-editor {
    min-height: 300px;
}
</style>
